#include "ComboView.h"
#include "ui_ComboView.h"

ComboView::ComboView(QWidget *parent) :
	INoteView(parent),
	ui(new Ui::ComboView)
{
	ui->setupUi(this);

	connect(ui->btnAddNote,SIGNAL(clicked()),SIGNAL(onBtnAddNote()));
	connect(ui->comboBox,SIGNAL(currentIndexChanged(int)),SLOT(onItemSelected(int)));
	connect(ui->btnRemoveNote,SIGNAL(clicked()),SLOT(onBtnRemoveItem()));
	connect(ui->btnEditNote,SIGNAL(clicked()),SLOT(onBtnEdit()));

	ui->btnAddNote->setStyleSheet(getButtonStyle("add"));
	ui->btnRemoveNote->setStyleSheet(getButtonStyle("delete"));
	ui->btnEditNote->setStyleSheet(getButtonStyle("edit"));
}

ComboView::~ComboView()
{
	delete ui;
}

void ComboView::onNoteAdded(Note* note)
{
	ui->comboBox->insertItem(0,note->getUrl(),qVariantFromValue((void *) note));
	ui->comboBox->model()->sort(0);
}

void  ComboView::onNoteRemoved(Note* note)
{
	int index = ui->comboBox->findData(qVariantFromValue((void *) note));
	if(index == -1) return;
	ui->comboBox->removeItem(index);
	if(ui->comboBox->count() == 0){
		clearFields();
	}
}

void ComboView::onItemSelected(int index)
{
	Note* note = (Note*) ui->comboBox->itemData(index).value<void *>();

	if(note == NULL) return;

	ui->editLogin->setText(note->getLogin());
	ui->editPass->setText(note->getPass());
	ui->editComment->setText(note->getComment());
}

void ComboView::onBtnRemoveItem()
{
	int index = ui->comboBox->currentIndex();
	if(index == -1) return;
	Note* note = (Note*) ui->comboBox->itemData(index).value<void *>();
	if(_provider){
		_provider->removeNote(note);
	}
}

void ComboView::onBtnEdit()
{
	int index = ui->comboBox->currentIndex();
	if(index == -1) return;
	Note* note = (Note*) ui->comboBox->itemData(index).value<void *>();
	emit onBtnEditNote(note);
}

void ComboView::onNoteUpdated(Note* note)
{
	int index = ui->comboBox->findData(qVariantFromValue((void *) note));
	if(index == -1) return;

	ui->comboBox->setItemText(index,note->getUrl());
	/// TODO: set selection only if Note* note is current item
	onItemSelected(index);
	ui->comboBox->model()->sort(0);
}

void ComboView::clearFields()
{
	if(ui->comboBox->count() == 1) return;
	ui->editComment->setText("");
	ui->editLogin->setText("");
	ui->editPass->setText("");
}

